package controllers;

import java.util.List;

import models.Category;
import models.Key;
import play.data.validation.Required;
import play.data.validation.Validation;
import play.db.jpa.JPASupport.JPAQuery;
import play.mvc.Controller;

public class CategoriesController
	extends Controller {
	public static void addCategory() {
		List<Key> allKeys = Key.findAll();
		render(allKeys);
	}

	public static void addCategoryAction(@Required String cName, Long[] keys) {
		List<Category> categories = Category.findAll();
		if (Validation.hasErrors()) {
			render();
		}
		Category newCategory = Category.find("byName", cName).first();
		if (newCategory == null) {
			newCategory = new Category(cName);
			if (keys != null) {
				for (Long id : keys) {
					Key selectedKey = Key.find("byId", id).first();
					newCategory.setCategoryKey(selectedKey);
				}
			}
			newCategory.save();
		} else {
			Validation.isTrue("cName", Boolean.FALSE).message("Alredy exists");
			render("CategoriesController/addCategory.html");
		}
		Application.index();
	}
}
